package com.im.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.im.app.manager.ConversationManager;
import com.im.app.model.*;
import com.im.app.model.User;
import com.im.app.service.*;
import com.im.app.utils.*;
import com.im.app.utils.uuid.IdUtils;
import com.im.app.utils.uuid.RSAUtils;
import org.apache.http.impl.cookie.DateUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.core.exception.ImException;
import org.jim.core.packets.*;
import org.jim.core.utils.JsonKit;
import org.jim.core.utils.Md5;
import org.jim.server.JimServerAPI;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.ChatReqHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.tio.utils.hutool.DateUnit;
import org.tio.utils.hutool.DateUtil;

import javax.annotation.Resource;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/login")
@CrossOrigin
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    @Resource
    private IUserService userService;
    @Resource
    private ICodeService codeService;
    @Resource
    private IPersonhostService personhostService;
    @Resource
    private VisitorAvatarService visitorAvatarService;
    @Resource
    private ConversationsService conversationsService;
    @Resource
    private IGroupMemberService groupMemberService;
    @Resource
    private IPreFormService preFormService;
    @Resource
    private IAdminService adminService;
    @Resource
    private IFlowRecordLogsService flowRecordService;

    @Resource
    private IGroupService groupService;

    @PostMapping (value ="/server")
    public ResponseResult<Object> serverLogin(String codeStr, HttpServletRequest request){
        if(codeStr == null){
            return Response.makeErrRsp("卡密不能为空");
        }
        codeStr = codeStr.trim();
        Code code = codeService.getCodeByKamicode(codeStr);
        if(code == null){
            return Response.makeErrRsp("卡密有误");
        }else if(!"useceshi".equals(code.getKamitype()) && !"uselogin".equals(code.getKamitype())){
            return Response.makeErrRsp("卡密类型有误");
        }else if (code.getDisable() == 1){
            return Response.makeErrRsp("卡密已停用");
        }
        User user= userService.getUserBykamiCode(codeStr);
        if(null==user) {
            return Response.makeErrRsp("卡密有误");
        }
        if(Constants.KAMINOUSE.equals(code.getKamistatus())){ //未激活 需要去激活用户
            Calendar rightNow = Calendar.getInstance();
            if(Constants.USECESHI.equals(code.getKamitype())){
                rightNow.add(Calendar.HOUR,2);
            }else if(Constants.USELOGIN.equals(code.getKamitype())){
                rightNow.add(Calendar.DATE,code.getDays());
            }
            user.setActStatus(1);
            user.setEndTime(rightNow.getTime());
            boolean updateById =userService.updateById(user);
            if(updateById){
                code.setKamistatus(Constants.KAMIINUSE);
                code.setUsetime(new Date());
                code.setEndTime(rightNow.getTime());
                codeService.updateById(code);
            }
            if (code.getType() > 0 && code.getAdminId() != null &&  code.getAdminId() > 0){
                Admin admin = adminService.selectAdminById(code.getAdminId());
                FlowRecordLogs flowRecord = FlowRecordLogs.createRecord(admin,FlowRecordLogs.ACTIVE,code.getKamicode() + "登录卡密已激活");
                flowRecordService.insertFlowRecordLogs(flowRecord);
            }
        }
        if(new Date().getTime()>user.getEndTime().getTime()) {
            return Response.makeErrRsp("账号已到期");
        }
        if (user.getStatus()==0){
            return Response.makeErrRsp("账号已停用");
        }
        String ip= IpUtils.getIpAddr(request);
        user.setIp(ip);
        user.setIpAddress(IpToAddressUtil.getRealAddressByIP(ip));
        userService.updateById(user);
        personhostService.updateUsersByOpration(user);
        String token = TokenUtils.generateTokeCode();
        user.setToken(token);
        cacheUser(user);
        return Response.makeOKRsp().setData(user);
    }


    @GetMapping (value ="/getLoginCode/{t}")
    public ResponseResult<Object> getLoginCode(@PathVariable(value = "t") String t){
        t = t.replace("-","/");
        String code = null;
        String jsonStr = RSAUtils.decrypt(t);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        if(null != jsonObject){
            code = jsonObject.getString("code");
        }
        if (code == null ){
            return Response.makeErrRsp("请求失败");
        }
        String serverCode = TokenUtils.generateTokeCode();
        try {
            //设置一天
            JedisTemplate.me().set("android_"+serverCode,code,180);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Response.makeOKRsp().setData(serverCode);
    }

    @PostMapping (value ="/androidLogin")
    public ResponseResult<Object> androidLogin(String serverCode, HttpServletRequest request){
        if(serverCode == null){
            return Response.makeErrRsp("登录码为空");
        }
        String codeStr = null;
        try {
            //设置一天
            codeStr = JedisTemplate.me().get("android_" + serverCode, String.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        codeStr = codeStr.trim();
        Code code = codeService.getCodeByKamicode(codeStr);
        if(code == null){
            return Response.makeErrRsp("卡密有误");
        }else if(!"useceshi".equals(code.getKamitype()) && !"uselogin".equals(code.getKamitype())){
            return Response.makeErrRsp("卡密类型有误");
        }
        User user= userService.getUserBykamiCode(codeStr);
        if(null==user) {
            return Response.makeErrRsp("卡密有误");
        }
        if(Constants.KAMINOUSE.equals(code.getKamistatus())){ //未激活 需要去激活用户
            Calendar rightNow = Calendar.getInstance();
            if(Constants.USECESHI.equals(code.getKamitype())){
                rightNow.add(Calendar.HOUR,2);
            }else if(Constants.USELOGIN.equals(code.getKamitype())){
                rightNow.add(Calendar.DATE,code.getDays());
            }
            user.setActStatus(1);
            user.setEndTime(rightNow.getTime());
            boolean updateById =userService.updateById(user);
            if(updateById){
                code.setKamistatus(Constants.KAMIINUSE);
                code.setUsetime(new Date());
                codeService.updateById(code);
            }
        }
        if(new Date().getTime()>user.getEndTime().getTime()) {
            return Response.makeErrRsp("账号已到期");
        }
        if (user.getStatus()==0){
            return Response.makeErrRsp("账号已停用");
        }
        String ip= IpUtils.getIpAddr(request);
        user.setIp(ip);
        user.setIpAddress(IpToAddressUtil.getRealAddressByIP(ip));
        userService.updateById(user);
        personhostService.updateUsersByOpration(user);
        String token = TokenUtils.generateTokeCode();
        user.setToken(token);
        cacheUser(user);
        return Response.makeOKRsp().setData(user);
    }

    private static Map<String,Object> userCache = new HashMap<>();

    @PostMapping(value ="/client")
    public ResponseResult<Object> clientLogin(String k, HttpServletRequest request){
        if (null == k){
            return Response.makeErrRsp("当前链接已失效");
        }

        String codeStr = null;
        String t = null;
        String deviceId = null;
        Integer type = null;
        String jsonStr = RSAUtils.decrypt(k);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String joinUrl = null;
        if(null != jsonObject){
            codeStr = jsonObject.getString("codeStr");
            t = jsonObject.getString("t");
            deviceId = jsonObject.getString("id");
            type = jsonObject.getInteger("type");
            joinUrl = jsonObject.getString("href");
        }
        if(null == codeStr || null == deviceId || null == type){
            return Response.makeErrRsp("当前链接已失效");
        }

        Personhost personhost = null;

        if(type == 1){
             personhost=personhostService.getPersonhostByCode(codeStr);
        }else if(type == 2) {
             //独立域名
             String domain = "http://" + codeStr;
             personhost=personhostService.getPersonHostByDomain(domain);
        }
        if (personhost == null){
            return Response.makeErrRsp("当前链接已失效");
        }
        String groupId = personhost.getGroupId();
        String ip = IpUtils.getIpAddr(request);
        String mobile = getMobile(request);
        String kefuid = personhost.getUserId();
        String token = TokenUtils.generateTokeCode();
        User user = userService.getUserByDeviceId(kefuid, deviceId);
        User kefu = userService.getKefuUser(kefuid);
        if(null == user){
            user = userService.getUserByKefuIdAndIp(kefuid,ip);
//            if (user != null){
//                if (user.getRemark() != null){
//                    user.setRemark(user.getRemark()+" | "+"IP:"+ip+"=>"+ DateUtils.formatDate(new Date(),"MM-dd HH:mm"));
//                }else {
//                    user.setRemark("IP:"+ip);
//                }
//            }
        }else {
//            if (user.getRemark() != null){
//                user.setRemark(user.getRemark()+" | "+"ID:"+deviceId+"=>"+ DateUtils.formatDate(new Date(),"MM-dd HH:mm"));
//            }else {
//                user.setRemark("ID:"+deviceId);
//            }
        }
        if(user != null){
            if(user.getStatus()==2){
                return Response.makeErrRsp("用户在黑名单");
            }
            //用户有缓存 并登入过
            user.setLoginCount(user.getLoginCount()+1);
            user.setProxy(isProxyRequest(request));
            user.setJoinUrl(joinUrl);
            updateUser(token,deviceId,ip,user);
        }else {
            if (userCache.get(deviceId) != null){
                user = (User) userCache.get(deviceId);
//                if (user.getRemark() != null){
//                    user.setRemark(user.getRemark()+" | "+"ID:"+deviceId+"=>"+ DateUtils.formatDate(new Date(),"MM-dd HH:mm"));
//                }else {
//                    user.setRemark("ID:"+deviceId);
//                }
            }else {
                VisitorAvatar visitorAvatar =visitorAvatarService.getVisitorAvatarByRandom();
                if (visitorAvatar == null){
                    return Response.makeErrRsp("系统出错");
                }
                String nickname= visitorAvatar.getName();
                if (kefu != null && kefu.getNameType() != null && 1 == kefu.getNameType()){
                    int count = userService.getTodayVisitor(kefuid);
                    nickname = formatDateTime() + "_"+String.format("%03d",count);
                }
                String avatar = visitorAvatar.getAvatar();
                user = new User(deviceId,nickname,avatar,ip,IpToAddressUtil.getRealAddressByIP(ip),new Date(),ip,IpToAddressUtil.getRealAddressByIP(ip),new Date(),kefuid,new Date(),deviceId,mobile,token,1);
                user.setLoginCount(1);
                user.setProxy(isProxyRequest(request));
                user.setJoinUrl(joinUrl);
//                user.setRemark("init deviceId:"+deviceId+" | ip:"+ip+"=>"+ DateUtils.formatDate(new Date(),"MM-dd HH:mm"));
                try {
                    userService.save(user);
                    log.info("新进用户 {}",user.getUserId());
                }catch (Exception e){
                    log.error(e.getMessage());
                    log.error("新进用户失败 {}",user.getUserId());
                }
                if(groupId != null){
                    GroupMember groupMember = new GroupMember(groupId,user.getUserId(),nickname,avatar,GroupMemberType.ROLE_PUBLIC.getNumber(),0,new Date());
                    groupMemberService.save(groupMember);
                }
                visitorAvatar.setUCount(visitorAvatar.getUCount() +1);
                visitorAvatarService.updateById(visitorAvatar);
                userCache.put(deviceId,user);
            }
        }

        PreForm preForm = preFormService.selectFormByDeviceId(deviceId);
        if (preForm != null){
            preForm.setAvatar(user.getAvatar());
            preForm.setName(user.getName());
            preForm.setUserId(user.getUserId());
            preFormService.updatePreForm(preForm);
        }
        try {
            //创建会话
            if(null != groupId){
                createGroupConversation(user.getUserId(),groupId);
            }else{
                createConversations(user);
            }
        } catch (Exception e) {
            log.error("创建会话失败 {}",user.getUserId());
        }

        //游客创建后删除验证码
        try {
            JedisTemplate.me().delKey("clientLogin_" + t);
        } catch (Exception e) {
            return Response.makeErrRsp(e.getMessage());
        }
        if (kefu != null){
            user.setAvatarShow(kefu.getAvatarShow());
        }
        cacheUser(user);
        return Response.makeOKRsp().setData(user);
    }

    private String formatDateTime() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("MM-dd");
        return format.format(date);
    }

    @PostMapping(value ="/group")
    public ResponseResult<Object> groupLogin(String groupId,String deviceId,HttpServletRequest request){

        Group group = groupService.selectGroupsByGroupId(groupId);
        String ip = IpUtils.getIpAddr(request);
        String mobile = getMobile(request);
        if (group != null){
            String kefuid = group.getOwnerId();
            User youke = userService.getUserByDeviceId(kefuid,deviceId);
            String token = TokenUtils.generateTokeCode();
            if (youke == null){
                youke = userService.getUserByKefuIdAndIp(kefuid,ip);
            }
            if(youke != null){
                if(youke.getStatus()==2){
                    return Response.makeErrRsp("用户在黑名单");
                }
                //用户有缓存 并登入过
                updateUser(token,deviceId,ip,youke);
                GroupMember groupMember = groupMemberService.selectGroupMember(groupId,youke.getUserId());
                JimServerAPI.bindGroup(youke.getUserId(),groupId);
                if (groupMember == null){
                    groupMember = new GroupMember(groupId,youke.getUserId(),youke.getName(),youke.getAvatar(),GroupMemberType.ROLE_PUBLIC.getNumber(),0,new Date());
                    groupMemberService.save(groupMember);
                    ChatBody chatBody = group.updateMessageTip(groupMember.getNickname() + "进入群组");
                    sendTip(chatBody,groupId);
                }
            }else {
                VisitorAvatar visitorAvatar =visitorAvatarService.getVisitorAvatarByRandom();
                if (visitorAvatar == null){
                    return Response.makeErrRsp("系统出错");
                }
                String nickname= visitorAvatar.getName();
                String avatar = visitorAvatar.getAvatar();
                youke = new User(IdUtils.simpleUUID().replace("-",""),nickname,avatar,ip,IpToAddressUtil.getRealAddressByIP(ip),new Date(),ip,IpToAddressUtil.getRealAddressByIP(ip),new Date(),kefuid,new Date(),deviceId,mobile,token,1);
                userService.save(youke);
                GroupMember groupMember = new GroupMember(groupId,youke.getUserId(),nickname,avatar,GroupMemberType.ROLE_PUBLIC.getNumber(),0,new Date());
                groupMemberService.save(groupMember);
                JimServerAPI.bindGroup(youke.getUserId(),groupId);
                ChatBody chatBody = group.updateMessageTip(groupMember.getNickname() + "进入群组");
                sendTip(chatBody,groupId);
                visitorAvatar.setUCount(visitorAvatar.getUCount() +1);
                visitorAvatarService.updateById(visitorAvatar);
            }

            createGroupConversation(youke.getUserId(),groupId);

            Map<String,Object> map = new HashMap<>();
            map.put("user",youke);
            map.put("group",group);
            cacheUser(youke);
            return Response.makeOKRsp(map);
        }
        return Response.makeErrRsp("登录失败");
    }

    private void sendTip(ChatBody chatBody,String groupId){
        List<ImChannelContext> channelContexts = JimServerAPI.getByGroup(groupId);
        if (channelContexts == null || channelContexts.size() <= 0) return;
        ImPacket groupPacket = new ImPacket(Command.COMMAND_CHAT_REQ, JsonKit.toJsonBytes(chatBody));
        ChatReqHandler chatReqHandler = CommandManager.getCommand(Command.COMMAND_CHAT_REQ, ChatReqHandler.class);
        if (chatReqHandler != null){
            try {
                chatReqHandler.handler(groupPacket, channelContexts.get(0));
            } catch (ImException e) {
                e.printStackTrace();
            }
        }
    }


    @PostMapping(value = "/admin")
    public ResponseResult<Object> adminLogin(String code){
        return adminService.login(code);
    }



    public void updateUser(String token,String deviceId,String ip,User user){
        //用户有缓存 并登入过
        user.setToken(token);
        user.setDeviceId(deviceId);
        if(null!= ip && !"".equals(ip)){
            if ("117.154.101.132".equals(ip)){
                user.setIp("103.130.142.98");
                user.setIpAddress("柬埔寨 金边");
            }else {
                user.setIp(ip);
                user.setIpAddress(IpToAddressUtil.getRealAddressByIP(ip));
            }
        }
        user.setLastLoginTime(new Date());
        userService.updateById(user);
    }

    /**
     * 创建群会话记录
     */
    public void createGroupConversation(String userId,String groupId){
        //游客会话
        Conversations gConversations = conversationsService.selectByGroup(userId,groupId);
        if(null == gConversations){
            Conversations conversations = new Conversations();
            conversations.setOwnerUserId(userId);
            conversations.setConversationId(IdUtils.simpleUUID());
            conversations.setGroupId(groupId);
            conversations.setConversationType(ChatType.CHAT_TYPE_PUBLIC.getNumber());
            conversations.setUnreadCount(0);
            conversations.setIsPinned(0);
            conversations.setLastTime(new Date().getTime());
            ConversationManager.getManager().sendGroupChange(conversations);
            conversationsService.insert(conversations);
        }
    }


    /**
     * 游客登录创建会话记录
     * */
    public void createConversations(User user){
        String kefuId = user.getKefuId();
        User kefuUser = userService.getUserByUserId(kefuId);
        String  userId = user.getUserId();
        //客服会话
        Conversations kconversations = conversationsService.selectByUser(kefuId,userId);
        if(null == kconversations){
            Conversations conversations = new Conversations();
            conversations.setOwnerUserId(kefuId);
            conversations.setConversationId(Md5.getMD5(kefuId+userId));
            conversations.setUserId(userId);
            conversations.setConversationType(ChatType.CHAT_TYPE_PRIVATE.getNumber());
            conversations.setUnreadCount(kefuUser.getIsNotice());
            conversations.setIsPinned(0);
            conversations.setNickName(user.getName());
            conversations.setAvatar(user.getAvatar());
            conversations.setLastTime(new Date().getTime());
            conversations.setLastMessageId(IdUtils.simpleUUID());
            Map kMap = new HashMap();
            kMap.put("content","发现新用户！");
            kMap.put("fromType",1);
            kMap.put("msgType",0);
            JSONObject json = new JSONObject(kMap);
            conversations.setLastMessage(json.toString());
            ConversationManager.getManager().sendUserChange(conversations);
            conversationsService.insert(conversations);
        }else {
            if (1 == kconversations.getIsDeleted()){
                kconversations.setIsDeleted(0);
                conversationsService.update(kconversations);
                ConversationManager.getManager().sendUserChange(kconversations);
            }
        }
        //游客会话
        Conversations vconversations = conversationsService.selectByUser(userId,kefuId);
        if(null == vconversations){
            Conversations conversations = new Conversations();
            conversations.setOwnerUserId(userId);
            conversations.setConversationId(Md5.getMD5(userId+kefuId));
            conversations.setUserId(kefuId);
            conversations.setConversationType(ChatType.CHAT_TYPE_PRIVATE.getNumber());
            conversations.setUnreadCount(1);
            conversations.setIsPinned(0);
            conversations.setNickName(kefuUser.getName());
            conversations.setAvatar(kefuUser.getAvatar());
            conversations.setLastTime(new Date().getTime());
            conversations.setLastMessageId(IdUtils.simpleUUID());
            ConversationManager.getManager().sendUserChange(conversations);
            conversationsService.insert(conversations);
        }
    }


    @GetMapping("/getDomain/{t}")
    public ResponseResult<Object> getDomain(@PathVariable(value = "t") String t ,HttpServletRequest request){
        if (t == null){
            return Response.makeErrRsp("请求失败");
        }
        t = t.replace("-","/");
        String ip = IpUtils.getIpAddr(request);
        String code = null;
        Integer type = null;
        String deviceId = null;
        String jsonStr = RSAUtils.decrypt(t);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        if(null != jsonObject){
            code = jsonObject.getString("code");
            type = jsonObject.getInteger("type");
            deviceId = jsonObject.getString("id");
        }
        if (code == null || type == null){
            return Response.makeErrRsp("请求失败");
        }

        if (type == 1){
            Personhost personhost = personhostService.getPersonhostByCode(code);
            if (personhost != null){
                String userId = personhost.getUserId();
                User kfUser = userService.getById(userId);
                if(null == kfUser){
                    return Response.makeErrRsp("请求失败");
                }
                User ykUser = null;
                ykUser = userService.getUserByDeviceId(userId,deviceId);
                if(null == ykUser){
                    ykUser = userService.getUserByKefuIdAndIp(userId,ip);
                }
                QueryWrapper<Personhost> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id",personhost.getUserId());
                queryWrapper.eq("leixing",4);
                List<Personhost> list = personhostService.list(queryWrapper);
                Personhost person = null;
                if (list != null && list.size() > 0){
                    person = list.get(0);
                }
                if (person != null){
                    String keyGen = keyGenerator();
                    Map map = new HashMap();
                    map.put("host",person);
                    map.put("t",keyGen);
                    map.put("iswechat",kfUser.getIswechat());
                    if(null != ykUser){
                        PreForm preForm = preFormService.selectPreFormByUserId(ykUser.getUserId());
                        if(null != preForm) {
                            map.put("isPreForm",0);
                        }else{
                            map.put("isPreForm",kfUser.getIsPreForm());
                        }
                    }else{
                        map.put("isPreForm",kfUser.getIsPreForm());
                    }
                    return Response.makeOKRsp().setData(map);
                }
            }
        }else if(type == 2){
            String domain = "http://"+code;
            Personhost personhost = personhostService.getPersonHostByDomain(domain);
            if (personhost != null){
                String userId = personhost.getUserId();
                User kfUser = userService.getById(userId);
                if(null == kfUser){
                    return Response.makeErrRsp("请求失败");
                }
                User ykUser = null;
                ykUser = userService.getUserByDeviceId(userId,deviceId);
                if(null == ykUser){
                    ykUser = userService.getUserByKefuIdAndIp(userId,ip);
                }
                QueryWrapper<Personhost> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id",personhost.getUserId());
                queryWrapper.eq("leixing",4);
                Personhost person = personhostService.getOne(queryWrapper);
                if (person != null){
                    String keyGen = keyGenerator();
                    Map map = new HashMap();
                    map.put("host",person);
                    map.put("t",keyGen);
                    map.put("iswechat",kfUser.getIswechat());
                    if(null != ykUser){
                        PreForm preForm = preFormService.selectPreFormByUserId(ykUser.getUserId());
                        if(null != preForm) {
                            map.put("isPreForm",0);
                        }else{
                            map.put("isPreForm",kfUser.getIsPreForm());
                        }
                    }else{
                        map.put("isPreForm",kfUser.getIsPreForm());
                    }
                    return Response.makeOKRsp().setData(map);
                }
            }
        }
        return Response.makeErrRsp("请求失败");
    }

    /**
     * 强制下线
     * */
    @GetMapping("/loginOut")
    public ResponseResult<Object> loginOut(String code){
        User user = userService.getUserBykamiCode(code);
        if (null == user) {
            return Response.makeErrRsp("用户不存在");
        }
        String userId = user.getUserId();
        RespBody body = new RespBody();
        body.setCommand(Command.COMMAND_LOGIN_OUT_RESP);
        body.setData(userId);
        body.setMsg("您已被强制下线");
        ImPacket chatPacket = new ImPacket(Command.COMMAND_LOGIN_OUT_RESP,body.toByte());
        JimServerAPI.sendToUser(userId,chatPacket);
        JimServerAPI.remove(userId, "收到关闭请求!");
        return Response.makeOKRsp();
    }


    /**
     * 修改卡密账号
     * */
    @GetMapping("/updateCode")
    public ResponseResult<Object> updateCode(String code){
        User user = userService.getUserBykamiCode(code);
        Code kami = codeService.getCodeByKamicode(code);
        if (null == user || null == kami ) {
            return Response.makeErrRsp("卡密用户不存在");
        }
        if(!"uselogin".equals(kami.getKamitype())){
            return Response.makeErrRsp("卡密类型不为登录卡密");
        }
        String newCode=RandomNum.randomdaxie(10)+"-LG";
        user.setKamicode(newCode);
        userService.updateById(user);
        kami.setKamicode(newCode);
        codeService.updateById(kami);
        return Response.makeOKRsp();
    }

    private void cacheUser(User user){
        try {
            //设置一天
            JedisTemplate.me().set(user.getToken(),user,60*60*24);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public String getMobile(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        String os = "";
        if (userAgent.toLowerCase().contains("windows")) {
            os = "Windows";
        }else if (userAgent.toLowerCase().contains("android")) {
            os = "Android";
        } else if (userAgent.toLowerCase().contains("iphone")) {
            os = "iPhone";
        } else {
            os = userAgent;
        }
        if (userAgent.contains("MicroMessenger")){
            os += "(微信)";
        }
        return os;
    }

    public boolean isProxyRequest(HttpServletRequest request) {
        // 检查X-Real-IP头
        String xRealIP = request.getHeader("X-Real-IP");
        if (xRealIP != null && !xRealIP.isEmpty()) {
            return true;
        }
        return false;
    }


    public String keyGenerator() {
        String encode = "" ;
        try {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecretKey secretKey = keygen.generateKey();
            encode = Base64.getEncoder().encodeToString(secretKey.getEncoded());
            JedisTemplate.me().set("clientLogin_"+encode,encode,120);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encode;
    }

}
